package com.huaxin.common.view;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.huaxin.common.R;

/**
 * ListView下拉刷新，加载更多
 *
 * @author PHJ
 * @version 1.0
 * @time 2014-2-16
 */
public class PullListView extends ListView implements OnScrollListener {

    /**
     * 松开刷新状态
     */
    private final static int RELEASE_To_REFRESH = 0;

    /**
     * 下拉状态
     */
    private final static int PULL_To_REFRESH = 1;

    /**
     * 正在刷新状态
     */
    private final static int REFRESHING = 2;

    /**
     * 加载完成状态
     */
    private final static int DONE = 3;

    /**
     * 加载中状态
     */
    private final static int LOADING = 4;

    /**
     * Item滑动状态
     */
    private final static int FLING = 5;

    /**
     * 实际的padding的距离与界面上偏移距离的比例
     */
    private final static int RATIO = 3;

    /**
     * LayoutInflater对象
     */
    private LayoutInflater inflater = null;

    /**
     * 头部下拉刷新的布局
     */
    private LinearLayout headView = null;

    /**
     * 头部布局显示的textview
     */
    private TextView tipsTextview = null;

    /**
     * 上次更新时间TextView
     */
    private TextView lastUpdatedTextView = null;

    /**
     * 头部布局的图片
     */
    private ImageView arrowImageView = null;

    /**
     * 进度条
     */
    private ProgressBar progressBar = null;

//	/** 旋转动画 */
//	private RotateAnimation animation = null;
//
//	/** 旋转动画 */
//	private RotateAnimation reverseAnimation = null;

    /**
     * 用于保证startY的值在一个完整的touch事件中只被记录一次
     */
    private boolean isRecored = false;

    /**
     * 头部布局的宽度
     */
    private int headContentWidth = 0;

    /**
     * 头部布局的高度
     */
    private int headContentHeight = 0;

    /**
     * 底部布局的宽度
     */
    private int footContentWidth = 0;

    /**
     * 底部布局的高度
     */
    private int footContentHeight = 0;

    /**
     * 开始时候的y
     */
    private int startY = 0;

    /**
     * 第一个item的索引
     */
    private int firstItemIndex = 0;

    /**
     * 该listview的状态
     */
    private int state = 0;

    /**
     * 是否在滑动
     */
    private boolean isBack = false;

    /**
     * 下拉刷新监听
     */
    private OnRefreshListener refreshListener = null;

    /**
     * 是否可刷新
     */
    private boolean isRefreshable = false;

    private boolean isScrollToBottom; // 是否滑动到底部
    private View footerView; // 脚布局的对象
    private int footerViewHeight; // 脚布局的高度
    private boolean isLoadingMore = false; // 是否正在加载更多中

    private AnimationDrawable animationDrawable;
    private RotateAnimation animation,reverseAnimation;
    private LinearLayout lastUpdate;

    /**
     * 构造函数
     */
    public PullListView(Context context, String userId) {
        super(context);
        init(context);
    }

    /**
     * 构造函数
     */
    public PullListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        if (isInEditMode()) {
            return;
        }
        setCacheColorHint(context.getResources().getColor(R.color.transparent));
        inflater = LayoutInflater.from(context);

        headView = (LinearLayout) inflater.inflate(R.layout.pull_list_head,
                this, false);
        arrowImageView = (ImageView) headView
                .findViewById(R.id.head_arrowImageView);


        progressBar = (ProgressBar) headView
                .findViewById(R.id.head_progressBar);
        tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);



        measureView(headView);
        headContentHeight = headView.getMeasuredHeight() ;
        headContentWidth = headView.getMeasuredWidth();

        headView.setPadding(0, -1 * headContentHeight, 0, 0);
        headView.invalidate();

        addHeaderView(headView, null, false);
        setOnScrollListener(this);

        animation = new RotateAnimation(0, -180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(250);
        animation.setFillAfter(true);

        reverseAnimation = new RotateAnimation(-180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        reverseAnimation.setInterpolator(new LinearInterpolator());
        reverseAnimation.setDuration(200);
        reverseAnimation.setFillAfter(true);

        initFooterView();

        state = DONE;
        isRefreshable = false;
    }

    @Override
    public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,
                         int totalItemCount) {
        firstItemIndex = firstVisiableItem;
        if (getLastVisiblePosition() == (totalItemCount - 1)) {
            isScrollToBottom = true;
        } else {
            isScrollToBottom = false;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView arg0, int scrollState) {

        if (scrollState == SCROLL_STATE_IDLE
                || scrollState == SCROLL_STATE_FLING) {
            // 判断当前是否已经到了底部
            if (isScrollToBottom && !isLoadingMore) {
                isLoadingMore = true;
                // 当前到底部
                footerView.setPadding(0, 0, 0, 0);
                this.setSelection(this.getCount());
                if (refreshListener != null) {
                    refreshListener.onLoadingMore();
                }
            }


        }
    }

    private int touchPos;
    private int touchX, touchY;
    private SwipeItemLayout touchView;
    /**
     * allow to do everything
     */
    private boolean doNothing = false;
    private boolean isActionDownAndUp = false;


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (isRefreshable) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isActionDownAndUp = true;
                    if (firstItemIndex == 0 && !isRecored) {
                        isRecored = true;
                        startY = (int) event.getY();
                    }
                    // ever where record touch state
                    touchX = (int) event.getX();
                    touchY = (int) event.getY();
                    touchPos = pointToPosition(touchX, touchY);
                    final View view = getChildAt(touchPos
                            - getFirstVisiblePosition());
                    /**
                     * 不为空,有下面两种情况：<br>
                     * 1：被打开---此时忽略touch事件<br>
                     * 2：已关闭---此时需要情况记录
                     */
                    if (touchView != null) {
                        if (touchView.isOpen()) {
                            touchView.smoothCloseMenu();
                            touchView = null;
                            doNothing = true;
                            return true;
                        } else {
                            touchView = null;
                        }
                    }
                    if (view instanceof SwipeItemLayout) {
                        touchView = (SwipeItemLayout) view;
                    }
                    if (touchView != null) {
                        touchView.onSwipe(event);
                    }
                    isActionDownAndUp = false;
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    /**
                     * 滑动或隐藏时,不处理点击事件
                     */
                    isActionDownAndUp = true;
                    if (doNothing) {
                        doNothing = false;
                        isRecored = false;
                        isBack = false;
                        state = DONE;
                        return true;
                    }
                    if (state == FLING) {
                        state = DONE;
                        isRecored = false;
                        if (touchView != null) {
                            touchView.onSwipe(event);
                            return true;
                        }
                    } else {
                        if (state != REFRESHING && state != LOADING) {
                            if (state == DONE) {

                            }
                            if (state == PULL_To_REFRESH) {
                                // 由下拉刷新状态，到done状态
                                state = DONE;
                                changeHeaderViewByState();
                            }
                            if (state == RELEASE_To_REFRESH) {
                                // 由松开刷新状态，到done状态
                                // state = REFRESHING;
                                // changeHeaderViewByState();
                                onRefresh();
                            }
                        }
                    }
                    isRecored = false;
                    isBack = false;
                    isActionDownAndUp = false;
                    break;

                case MotionEvent.ACTION_MOVE:
                    /**
                     * 滑动或隐藏时,不处理点击事件
                     */
                    if (doNothing) {
                        return true;
                    }
                    int tempX = (int) event.getX();
                    int tempY = (int) event.getY();
                    /**
                     * 如果是下拉刷新时，此时的状态要么FLING要么不是，避免冲突<br>
                     * 如果是上拉加载时，此时的状态只可能有FLING
                     */
                    if (state == DONE && !isActionDownAndUp) {
                        if (touchX - tempX > 30 && Math.abs(touchY - tempY) < 5) {
                            state = FLING;
                        }
                    }
                    if (state == FLING) {
                        if (touchView != null) {
                            touchView.onSwipe(event);
                            return true;
                        }
                    } else {
                        if (!isRecored && firstItemIndex == 0) {
                            isRecored = true;
                            startY = tempY;
                        }

                        if (state != REFRESHING && isRecored && state != LOADING) {

                            // 保证在设置padding的过程中，当前的位置一直是在head，否则如果当列表超出屏幕的话，当在上推的时候，列表会同时进行滚动
                            // 可以松手去刷新了
                            if (state == RELEASE_To_REFRESH) {

                                setSelection(0);

                                // 往上推了，推到了屏幕足够掩盖head的程度，但是还没有推到全部掩盖的地步
                                if (((tempY - startY) / RATIO < headContentHeight)
                                        && (tempY - startY) > 0) {
                                    state = PULL_To_REFRESH;
                                    changeHeaderViewByState();
                                }
                                // 一下子推到顶了
                                else if (tempY - startY <= 0) {
                                    state = DONE;
                                    changeHeaderViewByState();
                                }
                                // 往下拉了，或者还没有上推到屏幕顶部掩盖head的地步
                            }
                            // 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
                            if (state == PULL_To_REFRESH) {

                                setSelection(0);

                                // 下拉到可以进入RELEASE_TO_REFRESH的状态
                                if ((tempY - startY) / RATIO >= headContentHeight) {
                                    state = RELEASE_To_REFRESH;
                                    isBack = true;
                                    changeHeaderViewByState();
                                }
                                // 上推到了顶端
                                else if (tempY - startY <= 0) {
                                    state = DONE;
                                    changeHeaderViewByState();
                                }
                            }

                            if (state == DONE) {
                                if (tempY - startY > 0) {
                                    state = PULL_To_REFRESH;
                                    changeHeaderViewByState();
                                }
                            }

                            if (state == PULL_To_REFRESH) {
                                headView.setPadding(0, -1 * headContentHeight
                                        + (tempY - startY) / RATIO, 0, 0);

                            }

                            if (state == RELEASE_To_REFRESH
                                    && ((tempY - startY) / RATIO - headContentHeight) < headContentHeight / 2) {
                                headView.setPadding(0, (tempY - startY) / RATIO
                                        - headContentHeight, 0, 0);
                            }

                        }
                    }
                    break;
            }
        }

        return super.onTouchEvent(event);
    }

    /**
     * 当状态改变时候，调用该方法，以更新界面
     */
    private void changeHeaderViewByState() {
        switch (state) {
            case RELEASE_To_REFRESH:
                progressBar.setVisibility(View.GONE);
                tipsTextview.setVisibility(View.VISIBLE);
                arrowImageView.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.startAnimation(animation);
                tipsTextview.setText("松开刷新");

                break;
            case PULL_To_REFRESH:
                progressBar.setVisibility(View.GONE);
                tipsTextview.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.setVisibility(View.VISIBLE);
                // 是由RELEASE_To_REFRESH状态转变来的
                if (isBack) {
                    isBack = false;
                    arrowImageView.clearAnimation();
                    arrowImageView.startAnimation(reverseAnimation);

                    tipsTextview.setText("下拉刷新");
                } else {
                    tipsTextview.setText("下拉刷新");
                }
                break;

            case REFRESHING:
                headView.setPadding(0, 0, 0, 0);
                progressBar.setVisibility(View.VISIBLE);
                arrowImageView.clearAnimation();
                arrowImageView.setVisibility(View.GONE);
                tipsTextview.setText("正在刷新...");
                break;
            case DONE:
                headView.setPadding(0, -1 * headContentHeight, 0, 0);
                progressBar.setVisibility(View.GONE);
                arrowImageView.clearAnimation();
                tipsTextview.setText("下拉刷新");
                arrowImageView.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 设置下拉刷新监听
     *
     * @param refreshListener 下拉刷新监听
     */
    public void setOnRefreshListener(OnRefreshListener refreshListener,
                                     Boolean isRefreshable) {
        this.refreshListener = refreshListener;
        this.isRefreshable = isRefreshable;
    }



    /**
     * 下拉刷新监听接口
     *
     * @author xhb
     * @version V1.0
     */
    public interface OnRefreshListener {
        public void onRefresh();

        /**
         * 上拉加载更多
         */
        public void onLoadingMore();

    }

    /**
     * 下拉刷新完成
     */
    public void onRefreshComplete() {
        state = DONE;
        changeHeaderViewByState();
    }

    /**
     * 下拉刷新时调用
     */
    public void onRefresh() {
        if (refreshListener != null) {
            state = REFRESHING;
            changeHeaderViewByState();
            refreshListener.onRefresh();
        }
    }

    private void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
                    MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

    public void setAdapter(BaseAdapter adapter) {
        super.setAdapter(adapter);
    }

    public void setLastUpdate(long time) {
    }

    /**
     * 初始化脚布局
     */
    private void initFooterView() {
        footerView = View
                .inflate(getContext(), R.layout.custom_list_foot, null);
        footerView.measure(0, 0);
        footerViewHeight = footerView.getMeasuredHeight();
        footerView.setPadding(0, -footerViewHeight, 0, 0);
        this.addFooterView(footerView);
    }

    /**
     * 隐藏脚布局
     */
    public void hideFooterView() {
        footerView.setPadding(0, -footerViewHeight, 0, 0);
        isLoadingMore = false;
    }



}
